package com.example.drools.spring.core.helper;

import cn.hutool.core.collection.CollectionUtil;
import com.example.drools.spring.entity.DroolModel;
import com.example.drools.spring.entity.DroolRule;
import com.example.drools.spring.entity.KieResoure;
import com.example.drools.spring.utils.JacksonUtil;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;

/**
 * @author ddsyw
 * @version 1.0
 * @date 2021/12/29 10:24 上午
 */
public class RuleTransformHelper {

    public static Optional<DroolModel> transform(String ruleStr) {
        if (StringUtils.isBlank(ruleStr)) {
            return Optional.empty();
        }
        return Optional.of(JacksonUtil.jsonToBean(ruleStr, DroolModel.class));
    }

    public static Map<String, KieResoure> transFromDroolModel(List<DroolModel> droolModels) {
        if (CollectionUtil.isEmpty(droolModels)) {
            return Collections.EMPTY_MAP;
        }
        return droolModels.stream().filter(RuleTransformHelper::checkRule).map(RuleTransformHelper::convert).collect(
            Collectors.toMap(item -> item.getPathName(), Function.identity()));
    }


    private static boolean checkRule(DroolModel droolModel) {
        return !Objects.isNull(droolModel) && !Objects.isNull(droolModel.getPathName()) && !Objects.isNull(droolModel.getPackageName()) && !CollectionUtil.isEmpty(droolModel.getDroolRules()) && !CollectionUtil.isEmpty(droolModel.getImportClass());
    }

    private static KieResoure convert(DroolModel droolModel) {
        KieResoure kieResoure = new KieResoure();
        kieResoure.setPathName(droolModel.getPathName());
        StringBuilder stringBuilder = new StringBuilder();
        //TODO transfer annotation
        stringBuilder.append("package ").append(droolModel.getPackageName()).append("\n");
        for (String string : droolModel.getImportClass()) {
            stringBuilder.append("import ").append(string).append("\n");
        }
        for (DroolRule droolRule : droolModel.getDroolRules()) {
            stringBuilder.append("rule ").append(droolRule.getRule()).append("\n");
            stringBuilder.append("when ").append("\n").append(droolRule.getWhen()).append("\n");
            stringBuilder.append("then ").append("\n").append(droolRule.getThen()).append("\n");
            stringBuilder.append("end").append("\n");
        }
        kieResoure.setResoure(stringBuilder.toString());
        return kieResoure;
    }
}
